/*
 * Context
 * Author: Johan Kristins
 *	
 */

#include "Context.h"
#include "GLRenderer.h"

Context* Context::m_pInstance = NULL;

Context::Context()
{
	m_pWnd = NULL;
	m_pRenderer = NULL;
	m_pTextureMgr = NULL;
	m_iLastGameTick = 0;
};

Context::Context(const Context&)
{

};

Context& Context::operator= (const Context&)
{
	return *this;
};

Context* Context::GetHandle()
{
	if (m_pInstance == NULL)
	{  
		m_pInstance = new Context;
	};
	return m_pInstance;

};

bool Context::Init()
{
	m_pWnd = new glWindow();
	if (!m_pWnd->Init("NEON 1.0", 0, 0, WND_WIDTH, WND_HEIGHT))
	{
		printf("Couldn't init the window\n");
		return false;
	};
	m_pRenderer = new GLRenderer();
	if (!m_pRenderer->Init())
	{
		printf("Couldn't init the renderer\n");
		return false;
	};
	m_pMeshMgr = new MeshMgr();
	if (!m_pMeshMgr->Init())
	{
		printf("Couldn't init the mesh manager\n");
		return false;
	};
	m_pTextureMgr = new TextureMgr();
	if (!m_pTextureMgr->Init())
	{
		printf("Couldn't init the texture manager\n");
		return false;
	};
	m_pGameLogic = new GameLogic();
	if (!m_pGameLogic->Init())
	{
		printf("Couldn't intit the game logic\n");
		return false;
	};
	printf("The game has been init\n");
	return true;
};

void Context::Run()
{
	while(m_pWnd->MessagePump())
	{
		int iTick = ::GetTickCount();
		if ((iTick - m_iLastGameTick) > FRAME_RATE)
		{
			//Do game logic here
			m_pGameLogic->Run();
			
			m_iLastGameTick = iTick;
		};
		m_pRenderer->Run();
		m_pWnd->Swap();
		::Sleep(10);
	};
};

void Context::Close()
{
	m_pWnd->Exit();
	delete m_pWnd;
	m_pWnd = NULL;

	m_pGameLogic->Close();
	delete m_pGameLogic;
	m_pGameLogic = NULL;

	m_pRenderer->Close();
	delete m_pRenderer;
	m_pRenderer = NULL;

	m_pMeshMgr->Close();
	delete m_pMeshMgr;
	m_pMeshMgr = NULL;

	m_pTextureMgr->Close();
	delete m_pTextureMgr;
	m_pTextureMgr = NULL;
};